/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sorting;

/**
 *
 * @author Akram Mellice
 */
public final class QuickSort<T extends Comparable> extends Sort<T> {

    public QuickSort(T[] array, Class<T> classType) {
        super(array, classType);
    }

    private void divide(int start, int end) {
        if (start < end) {
            int mid = partition(start, end);
            divide(start, mid - 1);
            divide(mid + 1, end);
        }
    }

    private int partition(int start, int end) {
        T pivot = array[pickPivotIndex(start, end)];
        int i = start - 1, j;
        for (j = i + 1; j < end; j++) {
            if (array[j].compareTo(pivot) < 0) {
                T tmp = array[j];
                array[j] = array[++i];
                array[i] = tmp;
            }
        }
        T tmp = array[++i];
        array[i] = pivot;
        array[pickPivotIndex(start, end)] = tmp;
        return i;
    }

    /**
     * get the pivot
     * @param start is the start index of the partition
     * @param end is the end index of the partition
     * @return pivot index in the array
     */
    private int pickPivotIndex(int start, int end) {
        return end;
    }

    /**
     * Sort using Quick Sort algorithm
     * O(n lgn)
     */
    @Override
    public void sort() {
        divide(0, array.length - 1);
    }
}
